package com.qf.shiro;

import com.qf.pojo.DtsAdmin;
import com.qf.pojo.DtsPermission;
import com.qf.pojo.DtsRole;
import com.qf.service.DtsAdminService;
import com.qf.service.DtsPermissionService;
import com.qf.service.DtsRoleService;
import com.qf.util.bcrypt.BCrypt;
import com.qf.util.bcrypt.BCryptPasswordEncoder;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

/**
 * @author 千锋教育
 * @Company http://www.mobiletrain.org/
 * @Version 1.0
 */
public class AdminAuthorizingRealm extends AuthorizingRealm {
    @Autowired
    DtsAdminService dtsAdminService;
    @Autowired
    DtsRoleService dtsRoleService;
    @Autowired
    DtsPermissionService dtsPermissionService;

    //提供授权信息
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        DtsAdmin dtsAdmin = (DtsAdmin) principals.getPrimaryPrincipal();
        Integer[] roleIds = dtsAdmin.getRoleIds();

        Set<String> roles= dtsRoleService.findByRoleIds(roleIds);

        Set<String> permission=dtsPermissionService.findPermissionByIds(roleIds);

        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.setRoles(roles);
        authorizationInfo.setStringPermissions(permission);
        return authorizationInfo;
    }


    //提供认证信息
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String username = (String) token.getPrincipal();

        String password = new String((char[])token.getCredentials());


        DtsAdmin dtsAdmin=dtsAdminService.findUsername(username);
        if (dtsAdmin==null){
            throw new UnknownAccountException("未知账户");
        }
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

        if(dtsAdmin.getPassword()==null||!passwordEncoder.matches(password,dtsAdmin.getPassword())){
            throw new CredentialsException("密码错误");
        }
        if(dtsAdmin.getDeleted()){
            throw new LockedAccountException("账户已锁定");
        }

        AuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(dtsAdmin,password,dtsAdmin.getUsername());
        return authenticationInfo;
    }
}
